package com.leyou.trade.service.impl;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.UserContext;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.trade.entity.CartItem;
import com.leyou.trade.repository.CartRepository;
import com.leyou.trade.service.CartService;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
public class CartServiceImpl implements CartService {
    @Resource
    private CartRepository repository;
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private ItemClient itemClient;

    @Override
    public void saveCartItem(CartItem cartItem) {
        //获取用户信息
        UserDetail user = UserContext.getUser();
        //查询购物车商品
        String id = createId(cartItem.getSkuId());
        SkuDTO skuDTO = itemClient.querySkuById(cartItem.getSkuId());
        Optional<CartItem> optional = repository.findById(id);
        if (optional.isPresent()){
            Integer num = cartItem.getNum();
            cartItem = optional.get();
            cartItem.setNum(num+cartItem.getNum());
        }
        cartItem.setId(id);
        cartItem.setTitle(skuDTO.getTitle());
        cartItem.setUserId(user.getId());
        cartItem.setUpdateTime(new Date());
        repository.save(cartItem);
    }

    @Override
    public List<CartItem> listCartItem() {
        Long id = UserContext.getUser().getId();
        List<CartItem> items = repository.findByUserId(id, Sort.by("updateTime").descending());
        return items;
    }

    @Override
    public void addCartItem(Long skuId, Integer num) {
        mongoTemplate.update(CartItem.class)
                .matching(Query.query(Criteria.where("_id").is(createId(skuId))))
                .apply(Update.update("num",num).currentDate("updateTime"))
                .first();
    }

    @Override
    public void deleteCartItem(Long skuId) {
        repository.deleteById(createId(skuId));
    }
    @Override
    public void deleteCartItemByIds(List<Long> ids){ids.forEach(id->repository.deleteById(createId(id)));}

    private String createId(Long skuId){
        return String.format("u%ds%d", UserContext.getUser().getId(), skuId);
    }
}
